import sys
import os
import numpy as np
import cv2
import time

C, R = 100, 300

def load_image(filename):
    img = cv2.imread(filename)
    img = cv2.resize(img, (C, R))
    return img

def flatten_image(img):
    # 生成消除边缘的mask
    mask = np.zeros(img.shape, dtype=np.uint8)
    mult = 4
    mask[5*mult:47*mult, 1*mult:(C-1*mult+1)] = int(255)

    # 预处理
    # 滤波
    #img = cv2.bilateralFilter(img, 0, 100, 1)
    img = cv2.medianBlur(img, 3)
    #img = cv2.GaussianBlur(img, (5,5), 0)
    #img = cv2.blur(img, (3, 3))

    # 去掉边缘
    img = np.minimum(img, mask)

    # 拉直,供聚类算法使用
    row, col, n = img.shape
    img = img.reshape((row*col, n))

    return img, row, col

def better_image(img, func):
    #mask = np.ones(img.shape, dtype=np.uint8) * 255
    #mult = 4
    #mask[5*mult:47*mult, 1*mult:(C-1*mult+1)] = int(0)
    #img = np.maximum(img, mask)

    mask = np.zeros(img.shape, dtype=np.uint8)
    mult = 4
    mask[5*mult:47*mult, 1*mult:(C-1*mult+1)] = int(255)
    img = np.minimum(img, mask)

    # 预处理
    # 滤波
    #img = cv2.bilateralFilter(img, 0, 100, 1)
    #img = cv2.medianBlur(img, 3)
    # 去掉边缘
    #img = np.minimum(img, mask)

    if func == 'ScaleAbs':
        new_img = cv2.convertScaleAbs(img, alpha=1, beta=100)
    elif func == 'NormalizeL1':
        new_img = cv2.normalize(img, dst=None, norm_type=cv2.NORM_L1, mask=mask)
    elif func == 'NormalizeL2':
        new_img = cv2.normalize(img, dst=None, norm_type=cv2.NORM_L2, mask=mask)
    elif func == 'NormalizeMM':
        new_img = cv2.normalize(img, dst=None, alpha=255, beta=0, norm_type=cv2.NORM_MINMAX, mask=mask)
    elif func == 'EqualizeHist':
        new_img = cv2.equalizeHist(img)
    elif func == 'AdaptHist':
        new_img = cv2.createCLAHE(3,(8,8)).apply(img)
    return new_img
